/*

 RabbitMQ操作类封装

 对amqp模块进行二次封装

*/

const amqpLib = require('amqplib/callback_api')

class Amqp {
	
	constructor(common, config) {
		this.common = common
		this.config = config
		const {host, port, vhost, user, pwd} = this.config
		amqpLib.connect(`amqp://${user}:${pwd}@${host}:${port}/${vhost}`, (err, conn) => {
			if(err !== null) {
				console.error(err)
				return
			}
			this.amqp = conn
			this.amqp.on('close', () => {
				console.error('amqp connection is close')
				common.writeLog('info', 'amqp connection is close')
			})
			this.amqp.on('error', (err) => {
				console.error(err)
				common.writeLog('error', `amqp connection error:${err}`)
				common.alertMsg('RabbitMQ连接挂啦', err)
			})
			console.log(`amqp vhost ${vhost} is connected`)
		})	
	}

	createChannel(name) {
		return new Promise((resolve, reject) => {
			this.amqp.createChannel((err, ch) => {
				if(err !== null) {
					console.error(err)
					reject({
						code: '-1023',
						msg: 'amqp create channel failed'
					})
					return
				}
				ch.on('close', (err) => {
					console.error('channel is close:', err || 'ok')
				})
				ch.send = this.send
				ch.receive = this.receive
				ch.ok = this.ok
				resolve(ch)
			})
		})
	}

	send(name, data) {
		this.assertQueue(name)
		this.sendToQueue(name, new Buffer(data))
	}

	receive(name, callback) {
		this.assertQueue(name)
		this.consume(name, (data) => {
			if(data !== null) {
				callback(data)
			}
		})
	}

	ok(data) {
		this.ack(data)
	}

}

module.exports = Amqp